<template>
	<u-popup :show="showSkuPopup" mode="center" :safeAreaInsetBottom="false" @close="close" @open="open" round="30rpx"
		style="width: 200%;" :customStyle="{width:'calc(100% - 40rpx)',position: 'relative',margin:'0 20rpx'}">
		<view class="py-[30rpx] relative">
			<view class="text-[42rpx] text-[#1E1F21] font-bold leading-[42rpx]  px-[20rpx] line-clamp-1">
				{{defaultCover}}
			</view>
			<scroll-view :style="[specsListMaxHeight]" scroll-y="true" class="specsList">
				<view class="item" v-for="(skuArr, skuArrKey) in r.result" :key="skuArrKey">
					<text class="title leading-[24rpx]">{{skuArrKey}}</text>
					<view class="specsValueList">
						<view class="specs flex" v-for="(sku, skuKey) in skuArr" :key="skuKey"
							:style="[specsStyle(sku)]" @click="bindEvent(sku, skuArr, skuArrKey)">
							<!-- 带有图片的sku -->
							<view v-if="sku.img" class="specs_img_box">
								<!-- 禁用遮罩层 -->
								<view class="specs_img_box_mask"></view>
								<!-- 图片 -->
								<image class="specs_img_box_cover" :src="sku.img" :style="{
								borderRadius: sku.img ? '15rpx' : '10rpx'
							}">
								</image>
								<!-- 预览按钮 -->
								<view class="specs_img_box_preview" @click.stop="preview(sku.img)">
									<image class="img"
										src="">
									</image>
								</view>
								<!-- 文字 -->
								<text class="specs_img_box_text t-c" :style="{
							color: sku.active ? themeRGB : '#999999',
							borderBottomLeftRadius: sku.img ? '15rpx' : '10rpx',
							borderBottomRightRadius: sku.img ? '15rpx' : '10rpx',
							textDecoration: sku.discard ? 'line-through' : '',
						}">{{sku.value}}</text>
							</view>
							<!-- 普通sku -->
							<text v-else class="specs_common" :style="{
						backgroundColor: sku.active ? themeRGBA : '',
						color: sku.active ? themeRGB : '#999999',
						textDecoration: sku.discard ? 'line-through' : '',
					}">
								{{sku.value}}
							</text>
						</view>
					</view>
				</view>
				<slot name="batching" class="mb-[20rpx]"></slot>
			</scroll-view>
			<view class="mx-[20rpx] mt-[50rpx]   text-[24rpx]">
				<view class="bg-[#F8F8F8] h-[52rpx] border-[#F3F3F3] px-[20rpx] items-center flex">
					<view class="text-[#666666]">
						已选规格:
					</view>
					<view class="flex text-[#1E1F21] ml-[10rpx]">
						{{getSelectedSkuAttrStr}}
						<text v-for="(item,index) in batchsprice" :key="index"
							class="mr-[10rpx] ml-[10rpx]">{{item.batchingName}}</text>
							<text class="ml-[10rpx]">{{selectSku?.weight}}{{unitslist[selectSku?.unit-1]?.label}}</text>
					</view>
				</view>
			</view>
			<view class="h-[66rpx] flex justify-between  mt-[60rpx] px-[20rpx] items-center">
				<view class="flex h-[46rpx] items-center">
					<view class="text-[#1E1F21] font-bold text-[28rpx]">
						总计
					</view>
					<view class="flex ml-[20rpx] text-[#FF3F51]">
						<view class="text-[24rpx] font-bold flex items-end">
							￥
						</view>
						<view class="text-[46rpx] leading-[46rpx]  font-bold">
							<view v-if="specType==2">
								{{selectSku.id && batchspricesa>0?.price!==''?selectSku.price+batchspricesa:selectSku.id && batchspricesa==''?selectSku.price:!selectSku.id && batchspricesa!==''?batchspricesa:'--'}}
							</view>
							<view v-if="specType==1">
								{{batchspricesa>0?.price?prices+batchspricesa:prices}}
							</view>
						</view>
					</view>

				</view>
				<view class="">
					<view class="btnBoxs flex items-center justify-center" @click="confirm(1)" v-if="num==0">
						<view class="">
							<u-icon name="plus" size="24rpx" color="#fff"></u-icon>
						</view>
						<view class="ml-[4rpx] flex items-center">
							加入购物车
						</view>
					</view>
					<view class="" v-else>
						<!-- <view class="flex">
							<view class="" @click="jaddshop(ishavue)" v-show="num>0">
								<view class="jaddcar">
									<u-icon name="minus" bold color="#FE861C" top="" size="10"></u-icon>
								</view>
							</view>
							<view class="numbershop" v-if="num>0">
								{{num}}
							</view>
							<view class="addcar" @click="addshop(bullsdetals.goodsInfo)">
								<view class="">
									<u-icon name="plus" bold color="#fff" size="12"></u-icon>
								</view>
							</view>
						</view> -->
						<!-- 	<u-number-box v-model="num" @change="confirm(0)" @overlimit="numsdf" class="flex"
							:max="specType==1?stockNum:selectSku.id && specType==2? selectSku.stock : showAreaStock[1]"
							:min="0"> -->
						<u-number-box v-model="num" @change="confirm(0)" @overlimit="numsdf" class="flex"
							:max="getbuyMaxNum()" :min="0">

							<template #minus>
								<view class="minus">
									<u-icon name="minus" bold color="#FE861C" size="12"></u-icon>
								</view>
							</template>
							<template #input>
								<text style="text-align: center;" class="input">{{num}}</text>
							</template>
							<template #plus>
								<view class="plus">
									<u-icon name="plus" bold color="#FFFFFF" size="12"></u-icon>
								</view>
							</template>
						</u-number-box>
					</view>
				</view>
			</view>
			<view class="absolute left-[0] z-[1000] w-[100%] flex justify-center text-[#fff]"
				:class="yiertype==0?'bottom-[-120rpx]':'bottom-[-200rpx]'">
				<u-icon name="close-circle" size="70rpx" color="#fff" @click="close"></u-icon>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import CryptoJS from "crypto-js";
	import {
		stringify
	} from "postcss";
	export default {
		name: "wu-sku",
		props: {
			data: {
				default: () => [],
				type: Array
			},
			// 是否显示sku组件
			// #ifdef VUE3
			modelValue: {
				default: false,
				type: Boolean
			},
			yiertype: {
				default: 0,
				type: Number
			},
			// #endif
			// #ifndef VUE3
			value: {
				default: false,
				type: Boolean
			},

			// #endif
			// 是否可以点击关闭
			isMaskClose: {
				default: false,
				type: Boolean
			},
			// 是否默认选中最低价格sku
			isSelectMinPriceSku: {
				default: true,
				type: Boolean
			},
			shopnum: {
				default: 1,
				type: [Number]
			},
			// 默认选中的sku下标
			selectSkuIndex: {
				default: null,
				type: [Number, String]
			},
			batchsprice: {
				default: () => [],
				type: Array
			}, //配料价格
			// 默认封面图
			defaultCover: {
				default: "",
				type: String
			},
			// 默认购买商品数量
			defaultNum: {
				default: 0,
				type: [Number, String]
			},
			// 主题色
			themeColor: {
				default: () => [60, 156, 255],
				type: Array
			},
			// 确认按钮文字
			btnConfirmText: {
				default: "确定",
				type: String
			},
			// 不相关sku是否禁用
			skuUnrelatedDisabled: {
				default: false,
				type: Boolean
			},
			// sku禁用时的样式
			skuDisabledStyle: {
				default: () => {
					return {}
				},
				type: Object
			},
			// 库存不足文字
			notStockText: {
				default: "库存不足",
				type: String
			},
			// 未选择完整的sku时的文字提示
			notSelectSku: {
				default: "请选择完整的sku属性",
				type: String
			},
			// 展示库存数量
			showStockNum: {
				default: true,
				type: Boolean
			},
			specType: {
				default: 1,
				type: [Number, String]
			},
			stockNum: {
				default: 0,
				type: [Number, String]
			},
			prices: {
				default: 0,
				type: [Number, String]
			},
			...uni.$w?.props?.sku
		},
		data() {
			return {
				inventorytype: 1, // 库存类型 1-商品库存不足 配料库存不足虚拟商品
				// sku所有属性得可能性集合
				res: {},
				// 拼接得字符
				spliter: '\u2299',
				// 组合数据
				r: {},
				// sku属性名合集
				// 机身颜色: '深空黑色',
				// 储存容量: '128G',
				// 套装: '快充套装',
				// keys = [机身颜色, 储存容量, 套装]
				keys: [],
				// 选中的sku的副本
				selectedCache: [],
				// 选中的sku
				selectSku: {},
				// 展示的区间价格
				showAreaPrice: [0, 0],
				// 展示的区间库存
				showAreaStock: [0, 0],
				// 购买的数量
				num: 0,
				// 主题色RGB
				themeRGB: '',
				// 主题色RGBA
				themeRGBA: '',
				// 是否使用带图sku
				isUseImgSku: false,
				// 是否v3
				// #ifdef VUE3
				isV3: true,
				// #endif
				// #ifndef VUE3
				isV3: false,
				// #endif
				// 显示sku
				showSkuPopup: false,
				// 从低向上的动画显示
				shopSpecsPopupStyleShow: false,
				// 透明度消失动画, 让他关闭时看上不不那么生硬
				skuPopupStyleShow: false,
				sdkf: 1,
				batchspricesa: 0, //配料价格之和
				unitslist: [{
					label: '克(g)',
					id: 1
				}, {
					label: '千克(kg)',
					id: 2
				}, {
					label: '毫升(ml)',
					id: 3
				}, {
					label: '升(L)',
					id: 4
				}, {
					label: '斤',
					id: 5
				}, {
					label: '两',
					id: 6
				}]
			}
		},
		onShow() {
			this.resetNum()
		},
		// methods 是一些用来更改状态与触发更新的函数
		methods: {
			/**
			 * 计算组合数据
			 */
			combineAttr(data, keys) {
				var allKeys = []
				var result = {}

				for (var i = 0; i < data.length; i++) {
					var item = data[i].sku_attrs;
					var values = [];

					for (var j = 0; j < keys.length; j++) {
						let key = keys[j];
						// 属性名
						let attr_info = this.getObjAppointAttr(item[key]);

						if (!result[key]) result[key] = [];
						if (result[key].indexOf(attr_info.value) < 0) result[key].push(item[key]);

						values.push(attr_info.value);
					}

					allKeys.push({
						path: values.join(this.spliter),
						sku: data[i].id,
						stock: data[i].stock
					})
				}

				for (let key in result) {
					let obj = {};
					result[key].forEach(item => {
						// 属性名
						let attr_info = this.getObjAppointAttr(item);
						// 如果本次的属性不存在 则 将该属性设置为空对象
						if (!obj[attr_info.name]) obj[attr_info.name] = {};
						// 本次要操作的属性 下面得赋值是为了防止已有属性被覆盖
						obj[attr_info.name].value = attr_info.value;
						obj[attr_info.name].active = false;
						obj[attr_info.name].disabled = false;
						// 如果不想关sku需要禁用
						if (this.skuUnrelatedDisabled) {
							obj[attr_info.name].discard = false; // 是否废弃
						}

						// 如果该sku属性是对象则取其中的name属性
						if (Object.prototype.toString.call(item) === '[object Object]') {
							obj[attr_info.name] = {
								...obj[attr_info.name],
								...item
							};
							this.isUseImgSku = true;
						}

					})
					result[key] = obj;
				}

				return {
					result: result,
					items: allKeys
				}
			},
			numsdf() {
				if (this.inventorytype == 1) {
					uni.showToast({
						title: "商品库存不足",
						icon: "none"
					})
				} else {
					uni.showToast({
						title: "配料库存不足",
						icon: "none"
					})
				}

			},
			getAllKeys(arr) {
				var result = []
				for (var i = 0; i < arr.length; i++) {
					result.push(arr[i].path)
				}
				return result;
			},
			//计算可以购买的最大数量
			getbuyMaxNum() {
				let skunum = this.specType == 1 ? this.stockNum : this.selectSku.stock
				if (this.batchsprice.length > 0) {
					//配料列表按数量排序
					let arr = JSON.parse(JSON.stringify(this.batchsprice))
					let arr1 = arr.sort((a, b) => a.stockNum - b.stockNum);
					if (skunum > arr1[0].stockNum) {
						this.inventorytype = 2
						return arr1[0].stockNum
					} else {
						this.inventorytype = 1
						return skunum
					}
				} else {
					this.inventorytype = 1
					return skunum
				}
			},
			/**
			 * 取得集合的所有子集「幂集」
			 arr = [1,2,3]
			
			     i = 0, ps = [[]]:
			         j = 0; j < ps.length => j < 1:
			             i=0, j=0 ps.push(ps[0].concat(arr[0])) => ps.push([].concat(1)) => [1]
			                      ps = [[], [1]]
			
			     i = 1, ps = [[], [1]] :
			         j = 0; j < ps.length => j < 2
			             i=1, j=0 ps.push(ps[0].concat(arr[1])) => ps.push([].concat(2))  => [2]
			             i=1, j=1 ps.push(ps[1].concat(arr[1])) => ps.push([1].concat(2)) => [1,2]
			                      ps = [[], [1], [2], [1,2]]
			
			     i = 2, ps = [[], [1], [2], [1,2]]
			         j = 0; j < ps.length => j < 4
			             i=2, j=0 ps.push(ps[0].concat(arr[2])) => ps.push([3])    => [3]
			             i=2, j=1 ps.push(ps[1].concat(arr[2])) => ps.push([1, 3]) => [1, 3]
			             i=2, j=2 ps.push(ps[2].concat(arr[2])) => ps.push([2, 3]) => [2, 3]
			             i=2, j=3 ps.push(ps[3].concat(arr[2])) => ps.push([2, 3]) => [1, 2, 3]
			                      ps = [[], [1], [2], [1,2], [3], [1, 3], [2, 3], [1, 2, 3]]
			 */
			powerset(arr) {
				var ps = [
					[]
				];
				for (var i = 0; i < arr.length; i++) {
					for (var j = 0, len = ps.length; j < len; j++) {
						ps.push(ps[j].concat(arr[i]));
					}
				}
				return ps;
			},
			/**
			 * 生成所有子集是否可选、库存状态 map
			 */
			buildResult(items) {
				var allKeys = this.getAllKeys(items);

				for (var i = 0; i < allKeys.length; i++) {
					var curr = allKeys[i];
					var sku = items[i].sku;
					var values = curr.split(this.spliter);
					var allSets = this.powerset(values)

					// 每个组合的子集
					for (var j = 0; j < allSets.length; j++) {
						var set = allSets[j]
						// 使用CryptoJS的MD5对原属性名加密 用来禁绝因特殊符号带来的属性名错误
						var key = CryptoJS.MD5(set.join(this.spliter)).toString();

						if (this.res[key]) {
							this.res[key].skus.push(sku)
						} else {
							this.res[key] = {
								skus: [sku]
							}
						}
					}
				}
			},
			trimSpliter(str, spliter) {
				// ⊙abc⊙ => abc
				// ⊙a⊙⊙b⊙c⊙ => a⊙b⊙c
				var reLeft = new RegExp('^' + spliter + '+', 'g');
				var reRight = new RegExp(spliter + '+$', 'g');
				var reSpliter = new RegExp(spliter + '+', 'g');
				return str.replace(reLeft, '')
					.replace(reRight, '')
					.replace(reSpliter, spliter)
			},
			/**
			 * 获取当前选中的属性
			 */
			getSelectedItem() {
				var result = [];

				let resObj = this.r.result;
				if (resObj) {
					Object.keys(resObj).forEach((key1, index) => {
						result[index] = "";
						Object.keys(resObj[key1]).forEach(key2 => {
							// 查找选中的属性
							let item = resObj[key1][key2];
							item.active ? result[index] = item.value : '';
						})
					})
				}

				return result
			},
			/**
			 * 无效属性点击
			 */
			handleDisableClick(sku, skuArrKey, index) {
				this.selectedCache[index] = sku;

				// 清空所有sku选中属性
				let resObj = this.r.result;
				Object.keys(resObj).forEach((key1, index) => {
					Object.keys(resObj[key1]).forEach(key2 => {
						// 查找选中的属性
						let item = resObj[key1][key2];
						item.active = false;
					})
				})

				// 删除无效属性的禁止状态 并 选中
				sku.active = true;
				sku.disabled = false;

				this.updateStatus(this.getSelectedItem());

				/**
				 * 恢复原来已选属性
				 * 遍历所有非当前属性行
				 *   1. 与 selectedCache 对比
				 *   2. 如果要恢复的属性存在（非 disable）且 和当前*未高亮行*已选择属性的*可组合*），高亮原来已选择的属性且更新
				 *   3. 否则什么也不做
				 */
				for (var i = 0; i < this.keys.length; i++) {
					var item = this.keys[i];
					if (item == skuArrKey) continue

					// 没有被禁用的属性 (可以被选择)
					if (this.selectedCache[i] && !this.selectedCache[i].disabled && !this.selectedCache[i].discard) {
						this.selectedCache[i].active = true;
						this.updateStatus(this.getSelectedItem())
					}
				}

			},

			/**
			 * 更新所有属性状态
			 */
			updateStatus(selected) {
				// 遍历sku属性名合集
				for (var i = 0; i < this.keys.length; i++) {
					// 如果这段看不懂将console.log的注释解开即可
					var key = this.keys[i];
					var data = this.r.result[key];
					var hasActive = !!selected[i];
					var copy = selected.slice();
					// console.log(key, '属性名合集')
					// console.log(i)
					// console.log(copy, '已选属性');
					// 遍历data所有属性
					Object.keys(data).forEach(dataKey => {
						var item = data[dataKey];
						if (selected[i] == item.value) return;
						copy[i] = item.value;
						// 加密后的属性名
						var curr = CryptoJS.MD5(this.trimSpliter(copy.join(this.spliter), this.spliter))
							.toString();
						// 从sku组合合集中找出这项
						var resCurr = this.res[curr];
						// console.log(this.res, 'sku组合合集')
						// console.log(curr, '合集加密名称')
						// console.log(this.trimSpliter(copy.join(this.spliter), this.spliter))
						// 如果存在这种组合
						if (resCurr) {
							// console.log(resCurr)
							if (this.skuUnrelatedDisabled) {
								item.discard = false;
							} else {
								item.disabled = false;
							}
						} else {
							if (this.skuUnrelatedDisabled) {
								item.discard = true;
							} else {
								item.disabled = true;
							}
							item.active = false;
						}
					})
				}

				// 获取当前选中的属性
				var result = selected.slice();
				// 如果所有属性都已选中
				if (result.every(item => item)) {
					// 将属性合成r.items中的sku名称
					let name = this.trimSpliter(result.join(this.spliter), this.spliter);
					// 查找sku
					let sku = this.r.items.find(item => item.path == name);
					// 如果找到该sku
					if (sku) {
						// 根据sku的sku属性(唯一标识，通常来说会是id)找到源数据中的匹配的那一项并选中;
						this.selectSku = JSON.parse(JSON.stringify(this.data.find(item => item.id == sku.sku)));
						// 重置数量
						this.num = Number(this.defaultNum);
					}
				} else {
					this.selectSku = {};
				}
			},
			bindEvent(sku, skuArr, skuArrKey) {
				// 如果该sku属性被废弃则直接返回
				if (sku.discard) return;

				if (!sku.active) {
					// 清空当前行的所有sku选中属性
					Object.keys(skuArr).forEach(key => {
						skuArr[key].active = false;
					})

					sku.active = true;

					// 当前选中的keys的index
					let index = this.keys.findIndex(item => item == skuArrKey);

					if (sku.disabled) {
						this.handleDisableClick(sku, skuArrKey, index);
					} else {
						this.selectedCache[index] = sku;
					}
				}
				//  else {
				// 	sku.active = false;
				// 	// 清空所有sku禁用状态
				// 	let resObj = this.r.result;
				// 	Object.keys(resObj).forEach((key1, index) => {
				// 		Object.keys(resObj[key1]).forEach(key2 => {
				// 			// 查找选中的属性
				// 			let item = resObj[key1][key2];
				// 			if (this.skuUnrelatedDisabled) {
				// 				item.discard = false;
				// 			} else {
				// 				item.disabled = false;
				// 			}
				// 		})
				// 	})
				// }

				this.updateStatus(this.getSelectedItem());
			},

			/**
			 * 选中最便宜价格的sku
			 */
			selectMinPriceSku() {
				let minPriceSku = null;
				this.data.forEach(sku => {
					// 如果为空则直接赋值
					if (minPriceSku === null) {
						minPriceSku = sku
					} else if (minPriceSku.price > sku.price) { // 如果比最小价格低 就赋值
						minPriceSku = sku
					}
				})

				for (var key in minPriceSku.sku_attrs) {
					let attr_info = this.getObjAppointAttr(minPriceSku.sku_attrs[key]);
					// 找出对应项并选中
					this.r.result[key][attr_info.name].active = true;
				}
				this.updateStatus(this.getSelectedItem());
			},

			/**
			 * 选中某项sku
			 * @param {Number} index 选中的skuIndex
			 */
			selectAppointSku(index) {
				// 视图更新后在更新选中的skuIndex
				this.$nextTick(() => {
					if (!this.data[index]) return console.error('请输入正确的sku下标');
					let sku_attrs = this.data[index].sku_attrs;
					for (var key in sku_attrs) {
						let attr_info = this.getObjAppointAttr(sku_attrs[key]);
						// 找出对应项并选中
						this.r.result[key][attr_info.name].active = true;
					}
					this.updateStatus(this.getSelectedItem());
				})
			},

			/**
			 * 找出区间数据
			 */
			findAreaData() {
				let minPrice = null;
				let maxPrice = 0;
				let minStock = null;
				let maxStock = 0;
				this.data.forEach(sku => {
					// 如果最小价格为空则直接赋值
					if (minPrice === null) {
						minPrice = sku.price;
					} else if (minPrice * 1 > sku.price * 1) { // 如果比最小价格低 就赋值
						minPrice = sku.price;
					}
					// 如果大于最大价格则赋值
					if (maxPrice < sku.price) {
						maxPrice = sku.price;
					}

					// 如果最小库存为空则直接赋值
					if (minStock === null) {
						minStock = sku.stock;
					} else if (minStock * 1 > sku.stock * 1) { // 如果比最小库存少 就赋值
						minStock = sku.stock;
					}
					// 如果大于最大库存则赋值
					if (maxStock * 1 < sku.stock * 1) {
						maxStock = sku.stock;
					}
				})
				// 赋值区间
				this.showAreaPrice = [minPrice, maxPrice];
				this.showAreaStock = [minStock, maxStock];
			},

			// 初始化
			init(data) {
				this.res = {}
				this.r = {};
				this.keys = [];
				this.selectSku = {}
				this.selectedCache = [];
				this.isUseImgSku = false;

				// skus 长度为空则没必要往下继续进行了
				if (!data.length) return;

				// 拼接主题色
				this.joinThemColor(this.themeColor);

				// 找出sku的可选属性的标题
				for (var attr_key in data[0].sku_attrs) {
					// 如果这个属性未定义存则跳过
					if (!(attr_key in data[0].sku_attrs)) continue;
					// 如果这个属性未赋值 或 不存在 则删除该属性
					if (data[0].sku_attrs[attr_key] === null || data[0].sku_attrs[attr_key] === undefined) delete data[0]
						.sku_attrs[attr_key];
					// 否则添加属性
					else this.keys.push(attr_key);
				}

				//计算组合数据
				this.r = this.combineAttr(data, this.keys);

				// 生成所有子集是否可选、库存状态 map
				this.buildResult(this.r.items);

				// 找到区间数据
				this.findAreaData();

				// 如果无库存不展示 则 更新一下数据 因为有可能某个属性没有库存
				if (this.notSelectSku) {
					this.updateStatus(this.getSelectedItem());
				}

				// 如果需要选中某项sku
				if (this.selectSkuIndex !== null && this.selectSkuIndex !== undefined && this.selectSkuIndex !== '') {
					this.selectAppointSku(Number(this.selectSkuIndex));
				} else if (this.isSelectMinPriceSku) {
					// 如果需要选中默认最便宜的sku
					this.selectMinPriceSku();
				}
			},

			// 确认事件
			confirm(e) {
				let stoknum = this.specType == 1 ? this.stockNum : this.specType == 2 ? this.selectSku.stock : 0
				if (stoknum < 1) {
					uni.showToast({
						icon: 'none',
						title: '库存不足'
					})
					return
				}
				if (e == 1) {
					this.num = 1
				}
				//当订单是多规格
				if (this.specType == 2) {
					// 如果已有选中的完整sku
					if (this.selectSku.id) {
						// 如果有库存
						if (this.selectSku.stock * 1 > 0) {
							// 按钮确认事件
							this.$emit('confirm', {
								sku: this.selectSku,
								skuText: this.getSelectedItem(),
								num: this.num * 1
							})
						}
					} else {
						uni.showToast({
							title: this.notSelectSku,
							icon: 'none',
							duration: 1500
						})
					}
				} else {
					this.$emit('confirm', {
						sku: this.selectSku,
						skuText: this.getSelectedItem(),
						num: this.num * 1,
						price: this.prices
					})
				}
				// this.$emit('skuChange', this.selectSku);
			},

			// 拼接主题色
			joinThemColor(n) {
				this.themeRGB = `rgb(${n[0]}, ${n[1]}, ${n[2]})`;
				this.themeRGBA = `rgba(${n[0]}, ${n[1]}, ${n[2]}, 0.1)`;
			},

			// 关闭sku组件
			close() {
				// #ifdef VUE3
				this.$emit('update:modelValue', false);
				// #endif

				// #ifndef VUE3
				this.$emit('input', false);
				// #endif

				// #ifdef H5
				// fix by mehaotian 处理 h5 滚动穿透的问题
				document.getElementsByTagName('body')[0].style.overflow = 'visible'
				// #endif

				this.$emit('close');

				this.skuPopupStyleShow = false;
				this.shopSpecsPopupStyleShow = false;

				setTimeout(() => {
					this.showSkuPopup = false;
				}, 300)
			},

			// 打开sku组件
			open() {
				// #ifdef VUE3
				this.$emit('update:modelValue', true);
				// #endif

				// #ifndef VUE3
				this.$emit('input', true);
				// #endif

				// #ifdef H5
				// fix by mehaotian 处理 h5 滚动穿透的问题
				document.getElementsByTagName('body')[0].style.overflow = 'hidden'
				// #endif

				this.$emit('open');

				this.showSkuPopup = true;

				setTimeout(() => {
					this.skuPopupStyleShow = true;
					this.shopSpecsPopupStyleShow = true;
				})
			},

			// 重置购买数量
			resetNum() {
				this.num = Number(this.defaultNum);
			},

			// 获取对象中指定属性
			getObjAppointAttr(obj, attr = 'name') {
				// 用来储存属性中对应的值
				let value = "";
				// 如果该sku属性是对象则取其中的name属性
				if (Object.prototype.toString.call(obj) === '[object Object]') {
					value = obj[attr];
				} else {
					value = obj;
				}

				// 使用CryptoJS的MD5对原属性名加密 用来禁绝因特殊符号带来的属性名错误
				let name = CryptoJS.MD5(value).toString();

				return {
					value,
					name
				}
			},

			// 预览图片
			preview(img) {
				uni.previewImage({
					urls: [img]
				});
			},

			// specs样式
			specsStyle(sku) {
				let style = {
					borderRadius: sku.img ? '15rpx' : '10rpx'
				};
				// 选中的样式
				if (sku.active) {
					style.border = `3rpx solid ${this.themeRGB}`;
				} else if (sku.disabled) { // 禁用的样式
					style.border = `3rpx solid transparent`;
					style.background = '#f3f3f3';
				} else { // 默认状样式 或 废弃样式
					style.background = '#fff';
					style.border = `3rpx solid #e4e4e4`;
				}

				if (sku.discard) { // 废弃的样式
					style = {
						...style,
						...this.skuDisabledStyle
					};
				}

				return style
			}
		},
		// computed 计算属性
		computed: {
			// 获取已选中的sku属性字符串
			getSelectedSkuAttrStr() {
				let attrArr = this.getSelectedItem();
				// 如果有未选中的数据
				if (attrArr.findIndex(item => !item) !== -1) {
					// 获取sku属性名
					let resultArr = Object.keys(this.r.result);
					// 未选中的sku属性名
					let noAttrNameArr = [];
					attrArr.forEach((item, index) => {
						if (!item) {
							noAttrNameArr.push(resultArr[index]);
						}
					})

					return `请选择：${noAttrNameArr.join('、')}`
				} else {
					return `${attrArr.join('，')}`
				}
				return this.getSelectedItem();
			},
			// 获取确认按钮显示文字
			btnConfirmShowText() {
				return this.selectSku.id && this.selectSku.stock * 1 < 1 ? this.notStockText : this.btnConfirmText
			},
			// 获取 specslist 最大高度
			specsListMaxHeight() {
				let style = {};
				// #ifndef APP-NVUE
				style.maxHeight = '55vh';
				// #endif
				// #ifdef APP-NVUE
				style.height = uni.getWindowInfo().screenHeight * 0.65 + 'rpx';
				// #endif

				return style
			}
		},
		// 监听
		watch: {
			data: {
				handler(n) {
					this.init(n);
				},
				deep: true
			},
			// #ifdef VUE3
			modelValue(n) {
				if (n) {
					this.open();
					this.init(this.data);
				} else {
					this.close()
				}
			},
			// #endif
			// #ifndef VUE3
			value(n) {
				if (n) {
					this.open();
					this.init(this.data);
				} else {
					this.close()
				}
			},
			// #endif
			num: {
				handler(n) {
					// console.log('进入监听88', n)
					// this.defaultNum=n
					this.$emit('numChange', n);
					// this.$emit('skuChange', this.selectSku);
				},
				immediate: true
			},
			selectSku(n) {
				this.$emit('skuChange', n);
			},
			themeColor(n) {
				this.joinThemColor(n);
			},
			selectSkuIndex(n) {
				this.selectAppointSku(Number(n));
			},
			defaultNum: {
				handler(n) {
					this.num = Number(n)
					// console.log('进入监听', n)
				},
				deep: true,
				immediate: true
			},
			batchsprice: {
				handler(n) {
					this.batchspricesa = 0
					n.forEach(item => {
						this.batchspricesa += Number(item.price)
					})
				},
				deep: true
			}
		},
		// 挂载时
		mounted() {
			// 赋值默认购买商品数量
			this.num = Number(this.defaultNum);
			console.log(this.num, "数量")
			this.init(this.data);
		}
	}
</script>

<style lang="scss" scoped>
	.btnBoxs {
		width: 186rpx;
		height: 66rpx;
		background: #FE861C;
		border-radius: 10rpx;
		font-size: 26rpx;
		line-height: 26rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
	}

	.specsList {
		// margin-bottom: 30rpx;
		padding: 0 20rpx;

		.item {
			padding-top: 50rpx;

			.title {
				font-size: 28rpx;
				color: #1E1F21;
				font-weight: bold;
			}

			.specsValueList {
				@include flex;
				flex-wrap: wrap;

				.specs {
					margin-bottom: 10rpx;
					margin-right: 30rpx;
					margin-top: 10rpx;

					.specs_common,
					.specs_img_box_text {
						font-size: 24rpx !important;
						height: 56rpx;
						display: flex;
						align-items: center;
						// font-weight: 500 !important;
					}

					&.disabled {
						.specs_img_box .specs_img_box_mask {
							position: absolute !important;
							left: 0 !important;
							right: 0 !important;
							bottom: 0 !important;
							top: 0 !important;
							background-color: rgba(0, 0, 0, 0.2) !important;
						}
					}

					&_img_box {
						position: relative;

						&_preview {
							position: absolute;
							background: rgba(0, 0, 0, 0.7);
							border-radius: 50%;
							padding: 10rpx;
							right: 8rpx;
							top: 8rpx;
							z-index: 2;

							.img {
								width: 25rpx;
								height: 25rpx;
								transform: scale(1.2);
							}
						}

						&_cover {
							width: 200rpx;
							height: 200rpx;
						}

						&_text {
							background: #302e2f;
							padding: 15rpx 20rpx;
							text-align: center;
						}
					}

					&_common {
						padding: 0rpx 14rpx;
					}
				}
			}
		}
	}

	.addcar {
		width: 44rpx;
		height: 44rpx;
		background-color: #FE861C;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.addcars {
		width: 44rpx;
		height: 44rpx;
		background-color: #cccccc;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.addcarsa {
		background-color: #FE861C;
		padding: 6rpx 10rpx;
		font-size: 24rpx;
		color: #fff;
		border-radius: 8rpx;
	}

	.addcarsas {
		background-color: #cccccc;
		padding: 6rpx 10rpx;
		font-size: 24rpx;
		color: #fff;
		border-radius: 8rpx;
	}

	.jaddcar {
		width: 42rpx;
		height: 42rpx;
		background-color: #fff;
		border: 1px solid #FE861C;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.numbershop {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #000000;
		padding: 0 20rpx;
	}

	.minus {
		width: 22px;
		height: 22px;
		border-width: 1px;
		border-color: #FE861C;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		@include flex;
		justify-content: center;
		align-items: center;
	}

	.input {
		padding: 0 20rpx;
	}

	.plus {
		width: 22px;
		height: 22px;
		background-color: #FE861C;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
</style>